<?php

define('DB_SERVER', "localhost");
define('DB_USER', "u433246760_pego");
define('DB_PASSWORD', "godstock");
define('DB_NAME', "stockmatrix");


class dbBroker{
	private static $nInstance = 0;
	private static $objInstance = NULL;
	private $mysqlObj;
	
	public static function Instance(){
		if(dbBroker::$nInstance == 0){
			dbBroker::$nInstance++;
			dbBroker::$objInstance = new dbBroker();
		}
		return dbBroker::$objInstance;
	}
	
	public static function Remove($obj){
		if(dbBroker::$nInstance > 0){
			dbBroker::$nInstance--;
			if(dbBroker::$nInstance == 0)
				unset($obj);
		}
	}
	
	private function __construct(){
		$this->mysqlObj = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
	}
	
	public function query($sqlString){
		//DEBUG:
		echo "<br><font color=\"#666666\">$sqlString</font>";
		
		if($this->mysqlObj->connect_error == FALSE){
			$result = $this->mysqlObj->query($sqlString);
			if($result)
				return $result;
		}
		
		return NULL;
	}
	
	public function getAssocArray($queryResult){
		if($queryResult->num_rows > 0)
			return $queryResult->fetch_assoc();
		
		return NULL;
	}
	
	/**
	 * verifica se esiste la tabella $tableName
	 * @param $tableName nome della tabella da verificare l'esistenza
	 */
	public function ExistTable($tableName){
		if($this->query("SELECT 1 FROM $tableName LIMIT 1") != NULL)
			return TRUE;
		return FALSE;
	}
	
	public function formatString($strQ){
		return $this->mysqlObj->escape_string($strQ);
	}
}


abstract class dbTable{
	protected $name;
	protected $keyField;
	protected $db;
	
	public function __construct($_name, $_keyField){
		$this->db = dbBroker::Instance();
		$this->name = $_name;
		$this->keyField = $_keyField;
		
		if($this->db->ExistTable($this->name) == FALSE){
			$this->CreateTable();
		}
	}
	
	protected function Insert($arrAssocVal){
		$sql = "INSERT INTO $this->name (";
		$sqlVal = " VALUES (";
		
		$isFirst = true;
		foreach ($arrAssocVal as $colName => $colValue){
			if($isFirst == false){
				$sql .= ", ";
				$sqlVal .= ", ";
			}
			else
				$isFirst = false;
			$sql .= "`$colName`";
			
			if(is_numeric($colValue))
				$sqlVal .= $colValue;
			else
				$sqlVal .= "\"".$this->db->formatString($colValue)."\"";
		}
		
		$sql .= ") ";
		$sqlVal .= ") ";
		
		$this->db->query($sql.$sqlVal);
	}
	
	public abstract function CreateTable();
	protected abstract function record2object($assocArrayRec);
	protected abstract function object2record($obj);
	
	//SOLO PER DEBUG
	public function Show(){
		echo "<h1>$this->name</h1>";
		echo "<table><border=1><tr>";
		foreach ($this->keyField as $col){
			echo "<td><b>$col</b></td>";
		}
		$result = $this->db->query("SELECT * FROM $this->name");
		while($row = $this->db->getAssocArray($result)){
			echo "<tr>";
			foreach ($row as $cell)
				echo "<td>$cell</td>";
			echo "</tr>";
		}
		
	}
}

?>